﻿using Longbow.GiteeAuth;
using Longbow.OAuth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Configuration;
using System;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// Gitee 授权认证服务扩展类
    /// </summary>
    public static class GiteeExtensions
    {
        /// <summary>
        /// 添加 Gitee 认证授权服务
        /// </summary>
        /// <param name="builder">认证实例</param>
        /// <param name="configureOptions">GiteeAuthenticationOptions 权限配置项回调方法</param>
        /// <returns>AuthenticationBuilder 实例</returns>
        public static AuthenticationBuilder AddGitee(this AuthenticationBuilder builder, Action<GiteeOptions> configureOptions = null) => builder.AddGitee(GiteeDefaults.AuthenticationScheme, GiteeDefaults.DisplayName, configureOptions);

        /// <summary>
        /// 添加 Gitee 认证授权服务
        /// </summary>
        /// <param name="builder">认证实例</param>
        /// <param name="authenticationScheme">Gitee 认证架构名称 默认值为 Gitee</param>
        /// <param name="configureOptions">GiteeAuthenticationOptions 权限配置项回调方法</param>
        /// <returns>AuthenticationBuilder 实例</returns>
        public static AuthenticationBuilder AddGitee(this AuthenticationBuilder builder, string authenticationScheme, Action<GiteeOptions> configureOptions = null) => builder.AddGitee(authenticationScheme, GiteeDefaults.DisplayName, configureOptions);

        /// <summary>
        /// 添加 Gitee 认证授权服务
        /// </summary>
        /// <param name="builder">认证实例</param>
        /// <param name="authenticationScheme">Gitee 认证架构名称 默认值为 Gitee</param>
        /// <param name="displayName">Gitee 显示名称 默认值为 Gitee</param>
        /// <param name="configureOptions">GiteeAuthenticationOptions 权限配置项回调方法</param>
        /// <returns>AuthenticationBuilder 实例</returns>
        public static AuthenticationBuilder AddGitee(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<GiteeOptions> configureOptions)
        {
            var config = builder.Services.BuildServiceProvider().GetRequiredService<IConfiguration>();
            builder.Services.Configure<GiteeOptions>(authenticationScheme, config.GetSection(nameof(GiteeOptions)));
            return OAuthExtensions.AddOAuth<GiteeOptions, LgbOAuthHandler<GiteeOptions>>(builder, authenticationScheme, displayName, configureOptions);
        }
    }
}
